package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.MenuItemCompany;
import cc.mrbird.febs.buss.service.IMenuItemCompanyService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.utils.FebsUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2021-10-08 17:25:36
 */
@Slf4j
@Validated
@Controller
public class MenuItemCompanyController extends BaseController {

    @Autowired
    private IMenuItemCompanyService menuItemCompanyService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "menuItemCompany")
    public String menuItemCompanyIndex(){
        return FebsUtil.view("menuItemCompany/menuItemCompany");
    }

    @GetMapping("menuItemCompany")
    @ResponseBody
    @RequiresPermissions("menuItemCompany:list")
    public FebsResponse getAllMenuItemCompanys(MenuItemCompany menuItemCompany) {
        return new FebsResponse().success().data(menuItemCompanyService.findMenuItemCompanys(menuItemCompany));
    }

    @GetMapping("menuItemCompany/all")
    @ResponseBody
    public FebsResponse getAll(MenuItemCompany f,HttpServletRequest req) {
        Enumeration enu=req.getParameterNames();
        Map<String,Object> map=new HashMap<String,Object>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        if(map.get("keyword")!=null&&StringUtils.isNotBlank(map.get("keyword").toString().trim())){
            map.put("name",map.get("keyword"));
        }
        List<MenuItemCompany> list=menuItemCompanyService.selectByMap(map);
        return new FebsResponse().success().data(list);
    }

    @GetMapping("menuItemCompany/list")
    @ResponseBody
    public FebsResponse menuItemCompanyList(QueryRequest request, HttpServletRequest req, MenuItemCompany menuItemCompany) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.menuItemCompanyService.findMenuItemCompanyDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "menuItemCompany/add")
    public String goMenuItemCompanyAdd() {
        return FebsUtil.view("menuItemCompany/menuItemCompanyAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "menuItemCompany/update/{id}")
    public String goMenuItemCompanyUpdate(@PathVariable String id, Model model) {
        MenuItemCompany obj= menuItemCompanyService.getById(id);
        model.addAttribute("obj",obj);
        return FebsUtil.view("menuItemCompany/menuItemCompanyUpdate");
    }

    @ControllerEndpoint(operation = "新增MenuItemCompany", exceptionMessage = "新增MenuItemCompany失败")
    @PostMapping("menuItemCompany")
    @ResponseBody
    public FebsResponse addMenuItemCompany(@Valid MenuItemCompany menuItemCompany) {
        this.menuItemCompanyService.add(menuItemCompany);
        return new FebsResponse().success();
    }

    @GetMapping("menuItemCompany/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteMenuItemCompany( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.menuItemCompanyService.deleteMenuItemCompany(ids);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改MenuItemCompany", exceptionMessage = "修改MenuItemCompany失败")
    @PostMapping("menuItemCompany/update")
    @ResponseBody
    public FebsResponse updateMenuItemCompany(MenuItemCompany menuItemCompany) {
        this.menuItemCompanyService.updateMenuItemCompany(menuItemCompany);
        return new FebsResponse().success();
    }

    @PostMapping(value = "menuItemCompany/fileUpload")
    @ResponseBody
    public void fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuffer sb=new StringBuffer();
        String msg="上传成功";
        String src="http://localhost/tFile/preFile/";
        Integer code=0;
        if (file.isEmpty()) {
            System.out.println("文件为空");
            code=1;
            msg="上传失败";
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://queue_file//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            FileInputStream fileInputStream=new FileInputStream(filePath + fileName);
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有："+sheetNum+"个sheet");
            //遍历工作簿中的所有数据
            for(int i = 0;i<1;i++) {
                //读取第i个工作表
                System.out.println("读取第"+(i+1)+"个sheet");
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
                //获取最后一行的num，即总行数。此处从0开始
                int maxRow = sheet.getLastRowNum();
                // for (int row = 0; row <1; row++) {
                for (int row = 1; row <= maxRow; row++) {
                    //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                    int maxRol = sheet.getRow(row).getLastCellNum();
                    XSSFRow r=sheet.getRow(row);
                    if(r.getCell(0)==null||StringUtils.isBlank(r.getCell(0).toString().trim())){
                        continue;
                    }
                    System.out.println("--------第" + row + "行的数据如下--------");
                    System.out.println(r.getCell(0));
                    MenuItemCompany menuItemCompany = new MenuItemCompany();
                    menuItemCompany.setName(r.getCell(0)+"");
                    menuItemCompany.setYjstcmc(r.getCell(0)+"");
                    menuItemCompany.setFwdx(r.getCell(1)+"");
                    menuItemCompany.setZbdw(r.getCell(2)+"");
                    menuItemCompany.setBjlx(r.getCell(3)+"");
                    menuItemCompany.setBltj(r.getCell(4)+"");
                    menuItemCompany.setFdblsj(r.getCell(5)+"");
                    menuItemCompany.setZtfl(r.getCell(6)+"");
                    menuItemCompany.setCnblsj(r.getCell(7)+"");
                    menuItemCompany.setLbsxmc(r.getCell(8)+"");
                    menuItemCompany.setLbdw(r.getCell(9)+"");
                    menuItemCompany.setSsyj(r.getCell(10)+"");
                    menuItemCompany.setBllc(r.getCell(11)+"");
                    menuItemCompany.setSfsf(r.getCell(12)+"");
                    menuItemCompany.setSfyj(r.getCell(13)+"");
                    menuItemCompany.setTsfs(r.getCell(14)+"");
                    menuItemCompany.setZxfs(r.getCell(15)+"");

                    menuItemCompany.setIsGgfw("0");
                    menuItemCompany.setIsQqzx("0");
                    menuItemCompany.setIsQyfw("0");
                    menuItemCompany.setIsRcfw("0");
                    menuItemCompany.setIsYwtb("0");
                    menuItemCompanyService.add(menuItemCompany);

                    /*for (int rol = 0; rol < maxRol; rol++){
                        System.out.println(rol+"-"+r.getCell(rol) + "  ");
                    }*/
                    System.out.println();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();

        }
        sb.append("{");

        sb.append("\"code\":"+code);

        sb.append("}");
        response.getWriter().write(sb.toString());
    }
}
